// socket.io specific code


var socket = io.connect("/chat");//, resource:"chat");
var socket_game = io.connect("/game");//, resource:"chat");

var game_vc = new GameViewModel(); // sustituir por game_vm


// socket chat...

socket.on('connect', function () {
    //$('#chat').addClass('connected');
    socket.emit('join', window.room);
    //message('System', 'Welcome to RanTS match. In this chat you can to talk with all players in the match. <a href="#"> Link to help </a>.');
    message('System', 'Bienvenido a una partida de RanTS. Tu objetivo será acabar con todos los hormigueros rivales. Si necesitas ayuda pincha en bla bla bla...');

});

socket.on('announcement', function (msg) {
    $('#lines').append($('<p>').append($('<em>').text(msg)));
});

socket.on('msg_to_room', message);

socket.on('reconnect', function () {
    $('#lines').remove();
    message('System', 'Reconnected to the server');
});

socket.on('reconnecting', function () {
    message('System', 'Attempting to re-connect to the server');
});

socket.on('error', function (e) {
    message('System', e ? e : 'A unknown error occurred');
});

function message (from, msg) {
    $('#lines').append($('<p>').append($('<b>').text(from), msg));
    game_vc.add_message(new Message(from, msg));

    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_chat').hasClass('active') == false) {
        game_vc.badge_chats += 1;
        $('span#badge_chats_node').html(game_vc.badge_chats);
    }
}





// socket game...

socket_game.on('connect', function () {
    console.log("socket_game conectado");
    socket_game.emit('join', window.game);
    //$('#container_game').css('display', 'block');
});

socket_game.on('delay', function (emit_time, player_delay) {
    $('#player_delay').html(player_delay); // testeando.. solo pruebas
    socket_game.emit('update_delay', emit_time);
});

socket_game.on('exception', function(msg, type){
    $.notify(msg, type);
});


socket_game.on('player_over', function(player_finish_id, player_finish_name){

    if (game_vc.player_id == player_finish_id){
        $.notify('¡Has perdido la partida! ¡Juega otra! link', 'info');
        
    } else {
        $.notify('El jugador ' + player_finish_name + ' ha sido eliminado.', 'info');
    }
    
    // Avisando mediante el CHAT.
    from = "System";
    msg = 'El jugador ' + player_finish_name + ' ha sido eliminado.';
    game_vc.add_message(new Message(from, msg));
});

socket_game.on('game_over', function(player_finish_id, player_finish_name){

    // Avisando mediante alerts.
    if (game_vc.player_id == player_finish_id){
        $.notify('La partida ha terminado. ¡Enhorabuena, tú eres el ganador! ¡Juega otra partida! link', 'success');
    } else {
        $.notify('La partida ha finalizado ' + player_finish_name + ' ha sido el ganador. Suerte en la próxima. ¡Juega otra partida! link', 'info');
    }
    
    // Avisando mediante el CHAT.
    from = "System";
    msg = 'La partida ha finalizado ' + player_finish_name + ' ha sido el ganador. Suerte en la próxima. ¡Jugad otra partida! link'
    game_vc.add_message(new Message(from, msg));
});


socket_game.on('battle_report', function(report_id, date_start_game, date_battle_report, player_start_name, base_start_x, base_start_y, ants_attack_start, ants_attack_finish, ants_attack_deads, player_finish_name, base_finish_x, base_finish_y, ants_defend_start, ants_defend_finish, ants_defend_deads, info){

    game_vc.add_battle_report(new BattleReport(report_id, date_start_game, date_battle_report, player_start_name, base_start_x, base_start_y, ants_attack_start, ants_attack_finish, ants_attack_deads, player_finish_name, base_finish_x, base_finish_y, ants_defend_start, ants_defend_finish, ants_defend_deads, info));
    
    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_reports').hasClass('active') == false) {
        game_vc.badge_reports += 1;
        $('span#badge_reports_node').html(game_vc.badge_reports);
    }
});

socket_game.on('movement_report', function(report_id, date_start_game, date_battle_report, player_start_name, base_start_x, base_start_y, player_finish_name, base_finish_x, base_finish_y, info){

    game_vc.add_movement_report(new MovementReport(report_id, date_start_game, date_battle_report, player_start_name, base_start_x, base_start_y, player_finish_name, base_finish_x, base_finish_y, info));
    
    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_reports').hasClass('active') == false) {
        game_vc.badge_reports += 1;
        $('span#badge_reports_node').html(game_vc.badge_reports);
    }
});


socket_game.on('uphold_report', function(report_id, date_start_game, date_battle_report, player_start_name, base_start_x, base_start_y, player_finish_name, base_finish_x, base_finish_y, ants_uphold_init, ants_uphold_finish, info){

    game_vc.add_battle_report(new BattleReport(report_id, date_start_game, date_battle_report, player_start_name, base_start_x, base_start_y, ants_attack_start, ants_attack_finish, ants_attack_deads, player_finish_name, base_finish_x, base_finish_y, ants_defend_start, ants_defend_finish, ants_defend_deads, info));
    
    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_reports').hasClass('active') == false) {
        game_vc.badge_reports += 1;
        $('span#badge_reports_node').html(game_vc.badge_reports);
    }
});



socket_game.on('bases', function(bases_ids, x_coordinates, y_coordinates, resources, ants, speed_bonus){
    console.log('Actualizando bases propias...');

    var aux_base_selected = $('select#base-selector').val();

    // limpiar todas las bases existentes, y luego añadir las que vengan.
    game_vc.clear_bases();

    for(var i=0; i<bases_ids.length; i++){
        game_vc.add_base(new Base(bases_ids[i], x_coordinates[i], y_coordinates[i], parseInt(resources[i]), ants[i]));
    }

    if (game_vc.base_selected == null) {
        game_vc.base_selected = $('select#base-selector').val();
        $.each($('.select_bases'), function(key, value){
            $(this).css('display', 'none');
        });
        $('#base_sel_'+game_vc.base_selected).css('display', 'block');
    } else {
        game_vc.base_selected = aux_base_selected;
        $('select#base-selector').val(game_vc.base_selected);
    }

    if(speed_bonus == true){
        game_vc.player_is_speed_bonus_base = true;
    } else {
        game_vc.player_is_speed_bonus_base = false;
    }

});

socket_game.on('players', function (players_ids, players_names, players_growth_points, players_kill_points, players_roles) {
    console.log('Actualizando players..');
    // second version
    //debugger;
    for(var i=0; i<players_ids.length; i++){
        game_vc.add_player(new Player(players_ids[i], players_names[i], players_growth_points[i], players_kill_points[i]), players_roles[i]);
    }

    // ordenar jugadores...
    // game_vc.players().sort();
    // game_vc.players.sortByProperty("player_points_growth");
});


socket_game.on('map', function(bases_ids, x_coordinates, y_coordinates, players_ids, players_names, players_roles, players_growth_points, players_kill_points, player_id, speed_bonus, levels, bonus, resources_limit){
    console.log('Actualizando mapa...');

    if (!(player_id == null) && (game_vc.player_id == null)) {
        game_vc.player_id = player_id;
        if (speed_bonus == true){
            game_vc.player_is_speed_bonus = true;
        }
    }

    for(var i=0; i<bases_ids.length; i++){
        game_vc.add_base_map(new BaseMap(bases_ids[i], x_coordinates[i], y_coordinates[i], players_ids[i], players_names[i], players_roles[i], players_growth_points[i], players_kill_points[i], levels[i], bonus[i], resources_limit[i]));
        if(game_vc.base_map_selected == bases_ids[i]){
            $('#base_map_' + bases_ids[i]).show();
            $('#base_map_action_' + bases_ids[i]).show();
        }
    }
});


function remove_resource() {
    $(this).parent().remove();

    event_resource = game_vc.get_event_resource($(this).attr('id'));

    if(event_resource) {
        game_vc.remove_event_resource(event_resource);
        if (game_vc.badge_events > 0){
            game_vc.badge_events -= 1;
            $('span#badge_events_node').html(game_vc.badge_events);
        }
    } else {
        $.notify('No existe este "movement_event_resource"', 'error');
    }
}

function remove_attack() {
    $(this).parent().remove();

    event_attack = game_vc.get_event_attack($(this).attr('id'));

    if(event_attack) {
        game_vc.remove_event_attack(event_attack);
        if (game_vc.badge_events > 0){
            game_vc.badge_events -= 1;
            $('span#badge_events_node').html(game_vc.badge_events);
        }
    } else {
        $.notify('No existe este "movement_event_attack"', 'error');
    }
}

function remove_uphold() {
    $(this).parent().remove();

    event_uphold = game_vc.get_event_uphold($(this).attr('id'));

    if(event_uphold){
        game_vc.remove_event_uphold(event_uphold);
        if (game_vc.badge_events > 0){
            game_vc.badge_events -= 1;
            $('span#badge_events_node').html(game_vc.badge_events);
        }
    } else {
        $.notify('No existe este "movement_event_uphold"', 'error');
    }
}

/*
    Update the event times
    Type Events:
        - Start Attack (attack_start)
        - Receive Attack (attack_receive)
*/
socket_game.on('time_event_attack', function(attack_id, type_movement, seconds, base_start_id, base_start_x, base_start_y, base_start_player, base_finish_id, base_finish_x, base_finish_y, base_finish_player, resources, num_ants){

    // TODO: AÑADIR ORDENADOS POR TIEMPO DE LLEGADA
    
    date = new Date();
    date.setSeconds(date.getSeconds() + parseInt(seconds));
    
    var event_attack = new EventAttack(attack_id, base_start_id, base_start_x, base_start_y, base_start_player, base_finish_id, base_finish_x, base_finish_y, base_finish_player, num_ants, resources, type_movement);
    
    game_vc.add_event_attack(event_attack);

    $('#' + event_attack.sel_event_id).countdown({
        until: date,
        compact: true,
        onExpiry: remove_attack,
    });

    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_events').hasClass('active') == false) {
        game_vc.badge_events += 1;
        $('span#badge_events_node').html(game_vc.badge_events);
    }

});



/*
    Update the event times
    Type Events:
        - Start Uphold (uphold_start)
        - Receive Uphold (uphold_receive)
        - Back Uphold (uphold_back)
*/
socket_game.on('time_event_uphold', function(uphold_id, type_movement, seconds, base_start_id, base_start_x, base_start_y, base_start_player, base_finish_id, base_finish_x, base_finish_y, base_finish_player, resources, num_ants){

    // TODO: AÑADIR ORDENADOS POR TIEMPO DE LLEGADA
    
    date = new Date();
    date.setSeconds(date.getSeconds() + parseInt(seconds));
    
    var event_uphold = new EventUphold(uphold_id, base_start_id, base_start_x, base_start_y, base_start_player, base_finish_id, base_finish_x, base_finish_y, base_finish_player, num_ants, resources, type_movement);
    
    game_vc.add_event_uphold(event_uphold);

    $('#' + event_uphold.sel_event_id).countdown({
        until: date,
        compact: true,
        onExpiry: remove_uphold,
    });

    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_events').hasClass('active') == false) {
        game_vc.badge_events += 1;
        $('span#badge_events_node').html(game_vc.badge_events);
    }

});


/*
    Update the event times
    Type Events:
        - Start Resource (resource_start)
        - Receive Resource (resource_receive)
        - Back Resource (resource_back)
*/
socket_game.on('time_event_resources', function(movement_resources_id, type_movement, seconds, base_start_id, base_start_x, base_start_y, base_start_player, base_finish_id, base_finish_x, base_finish_y, base_finish_player, num_workers, resources){

    // TODO: AÑADIR ORDENADOS POR TIEMPO DE LLEGADA
    
    date = new Date();
    date.setSeconds(date.getSeconds() + parseInt(seconds));
    
    var event_resource = new EventResource(movement_resources_id, base_start_id, base_start_x, base_start_y, base_start_player, base_finish_id, base_finish_x, base_finish_y, base_finish_player, num_workers, resources, type_movement);
    
    game_vc.add_event_resource(event_resource);

    $('#' + event_resource.sel_event_id).countdown({
        until: date,
        compact: true,
        //onExpiry: probando2,
        onExpiry: remove_resource,
    });

    // Tratar de hacer con knockout y no con jQuery... (actualizar una variable).
    if ($('#li_events').hasClass('active') == false) {
        game_vc.badge_events += 1;
        $('span#badge_events_node').html(game_vc.badge_events);
    }
});


socket_game.on('game_start', function(){
    // Comienza la partida
    actual_date = new Date();
    $('#count-time-up').countdown({
        since: actual_date,
        compact: true,
    });
});



    

// DOM manipulation
$(function () {
    $('#set-nickname').submit(function (ev) {
        socket.emit('nickname', $('#nick').val(), function (set) {
            if (set) {
                clear();
                //return $('#chat').addClass('nickname-set');
            }
            //$('#nickname-err').css('display', 'block');
        });

        // GAME
        socket_game.emit('nickname', $('#nick').val(), $('#role_selection').val(), function (set){
            if(set){
                //Cosas que hacer tras la conexión de un player ...
                $('#container_game').css('display', 'block');
                $('#container_login').css('display', 'none');

            } else {
                // otros errores...
                alert("Problemas, no hemos podido conectar con el socket game.");
            }
        });
        
        return false;
    });

    $('#send-message').submit(function () {
	    message('me', $('#message').val());
	    socket.emit('user message', $('#message').val());
	    clear();
	    $('#lines').get(0).scrollTop = 10000000;
	    return false;
    });

    $('#send-message2').submit(function () {
	    message('me', $('input#chat-msg').val());
	    socket.emit('user message', $('input#chat-msg').val());
        $('tbody#chat-lines').get(0).scrollTop = 100000;
	    $('input#chat-msg').val('').focus();
	    return false;
    });

    $('#main').on('submit', '.form-new-ants', function(){
        var form = $(this);
        var array_form = form.serializeArray();
        var type_ants = array_form[0]['value'];
        var num_ants = array_form[1]['value'];
        socket_game.emit('new_ant', type_ants, num_ants, parseInt(game_vc.base_selected), function(set){
            if(set[0]){
                form.find("input.input_num_ants").val('');
                $.notify("Hormigas construidas", 'success');
            } else {
                $.notify(set[1], 'error');
            }
        });
        return false;
    });

    $('#main').on('submit','.send-resources',function () {
        var base_origin_id = parseInt(game_vc.base_selected);
        var base_finish_id = parseInt($(this).data('iden').split('_')[2]);

        // Comprobación de si el hormiguero final está ocupado o no.
        base = game_vc.get_base_map_id(base_finish_id);
        if (base.player_id == null) {
            msg = 'Situación ilegal, el hormiguero de destino no pertenece a nadie.'
            $.notify(msg, 'error');
        }
        else {
            var resources = parseFloat($(this).find('input.input-resources').val());
            if(isNumber(resources)){
                socket_game.emit('movement_resources', base_origin_id, base_finish_id, resources, function(data){
                    if (data[0] ==  true){
                        $.notify('Envío de Recursos Enviado', 'success');
                    }
                });
                $(this).find('.input-resources').val('');
                
            } else {
                msg = 'Introduzca un número por favor.';
                $.notify(msg, 'warn');
            }
        }
        return false;
    });

    $('#main').on('submit', '.send-attack', function () {
        var base_origin_id = parseInt(game_vc.base_selected);
        var base_finish_id = parseInt($(this).data('iden').split('_')[2]);

        var ant_0 = parseFloat($(this).find('input.ant-0').val());
        var ant_1 = parseFloat($(this).find('input.ant-1').val());
        var ant_2 = parseFloat($(this).find('input.ant-2').val());
        var ant_3 = parseFloat($(this).find('input.ant-3').val());
        var ant_4 = parseFloat($(this).find('input.ant-4').val());
        var ant_5 = parseFloat($(this).find('input.ant-5').val());

        ants = {
            'ant_0': ant_0,
            'ant_1': ant_1,
            'ant_2': ant_2,
            'ant_3': ant_3,
            'ant_4': ant_4,
            'ant_5': ant_5,
        }

        var_form = $(this);

        if(ant_0 == 0 && ant_1 == 0 && ant_2 == 0 && ant_3 == 0 && ant_4 == 0 && ant_5 == 0){
            $.notify('Introduzca algún número por favor.', 'warn');
            $(this).find('input.ant-0').val('0');
            $(this).find('input.ant-1').val('0');
            $(this).find('input.ant-2').val('0');
            $(this).find('input.ant-3').val('0');
            $(this).find('input.ant-4').val('0');
            $(this).find('input.ant-5').val('0');
        } else if ( ( isNumberPos(ant_0) || ant_0 == "" ) && ( isNumberPos(ant_1) || ant_1 == "" ) && ( isNumberPos(ant_2) || ant_2 == "") && ( isNumberPos(ant_3) || ant_3 == "") && ( isNumberPos(ant_4) || ant_4 == "") && ( isNumberPos(ant_5) || ant_5 == "" ) ) {
            socket_game.emit('attack', base_origin_id, base_finish_id, ants, function(set){
                if(set[0] == true){
                    var_form.find('input.ant-0').val('0');
                    var_form.find('input.ant-1').val('0');
                    var_form.find('input.ant-2').val('0');
                    var_form.find('input.ant-3').val('0');
                    var_form.find('input.ant-4').val('0');
                    var_form.find('input.ant-5').val('0');
                    $.notify('Ataque Enviado', 'success');
                }
            });

        } else {
            $.notify('Introduzca números válidos por favor.', 'warn');
            $(this).find('input.ant-0').val('0');
            $(this).find('input.ant-1').val('0');
            $(this).find('input.ant-2').val('0');
            $(this).find('input.ant-3').val('0');
            $(this).find('input.ant-4').val('0');
            $(this).find('input.ant-5').val('0');
        }

        $('.div-ants-attack-time').hide();
        return false;
    });

    $('#main').on('submit', '.send-uphold', function () {
        var base_origin_id = parseInt(game_vc.base_selected);
        var base_finish_id = parseInt($(this).data('iden').split('_')[2]);

        var ant_0 = parseFloat($(this).find('input.ant-0').val());
        var ant_1 = parseFloat($(this).find('input.ant-1').val());
        var ant_2 = parseFloat($(this).find('input.ant-2').val());
        var ant_3 = parseFloat($(this).find('input.ant-3').val());
        var ant_4 = parseFloat($(this).find('input.ant-4').val());
        var ant_5 = parseFloat($(this).find('input.ant-5').val());

        ants = {
            'ant_0': ant_0,
            'ant_1': ant_1,
            'ant_2': ant_2,
            'ant_3': ant_3,
            'ant_4': ant_4,
            'ant_5': ant_5,
        }
        
        var_form = $(this);

        if(ant_0 == 0 && ant_1 == 0 && ant_2 == 0 && ant_3 == 0 && ant_4 == 0 && ant_5 == 0){
            $.notify('Introduzca algún número por favor.', 'warn');
            $(this).find('input.ant-0').val('0');
            $(this).find('input.ant-1').val('0');
            $(this).find('input.ant-2').val('0');
            $(this).find('input.ant-3').val('0');
            $(this).find('input.ant-4').val('0');
            $(this).find('input.ant-5').val('0');
        } else if ( ( isNumberPos(ant_0) || ant_0 == "" ) && ( isNumberPos(ant_1) || ant_1 == "" ) && ( isNumberPos(ant_2) || ant_2 == "") && ( isNumberPos(ant_3) || ant_3 == "") && ( isNumberPos(ant_4) || ant_4 == "") && ( isNumberPos(ant_5) || ant_5 == "" ) ) {
            socket_game.emit('uphold', base_origin_id, base_finish_id, ants, function(set){
                if(set[0] == true){
                    var_form.find('input.ant-0').val('0');
                    var_form.find('input.ant-1').val('0');
                    var_form.find('input.ant-2').val('0');
                    var_form.find('input.ant-3').val('0');
                    var_form.find('input.ant-4').val('0');
                    var_form.find('input.ant-5').val('0');
                    $.notify('Apoyo Enviado', 'success');
                }
            });

        } else {
            $.notify('Introduzca números válidos por favor.', 'warn');
            $(this).find('input.ant-0').val('0');
            $(this).find('input.ant-1').val('0');
            $(this).find('input.ant-2').val('0');
            $(this).find('input.ant-3').val('0');
            $(this).find('input.ant-4').val('0');
            $(this).find('input.ant-5').val('0');
        }

        $('.div-ants-uphold-time').hide();
        return false;
        
        
    });

    $('#main').on('change', '#base-selector', function () {
        game_vc.base_selected = $('select#base-selector').val();
        $.each($('.select_bases'), function(key, value){
            $(this).css('display', 'none');
        });
        $('#base_sel_'+game_vc.base_selected).css('display', 'block');
    });

    function clear() {
        $('#message').val('').focus();
    };


    $('#main').on('focusout keyup change', 'input.ants-attack', function () {
        
        input_nodes = $(this).parent().parent();
        var selector_ants = "ants-attack";

        // Seleccionamos el tipo de velocidad.
        var speed_ant = select_speed_type_ant(input_nodes, selector_ants);

        if (speed_ant == -1){ // Si no hay ninguno ocultamos módulo de tiempo.
            node_time = $(this).parent().parent().siblings("div.div-ants-attack-time");
            node_time.hide();
        }
        else { // Si hay, lo mostramos.
            selector_div_time = "div.div-ants-attack-time";
            show_time_type_ant2($(this), speed_ant, selector_div_time);
        }
    });

    $('#main').on('focusout keyup change', 'input.ants-uphold', function () {

        input_nodes = $(this).parent();
        var selector_ants = "ants-uphold";

        // Seleccionamos el tipo de velocidad.
        var speed_ant = select_speed_type_ant(input_nodes, selector_ants);

        if (speed_ant == -1){ // Si no hay ninguno ocultamos módulo de tiempo.
            node_time = $(this).parent().siblings("div.div-ants-uphold-time");
            node_time.hide();
        }
        else { // Si hay, lo mostramos.
            selector_div_time = "div.div-ants-uphold-time";
            show_time_type_ant($(this), speed_ant, selector_div_time);
        }
    });

    $('#main').on('focusout keyup change', 'input.input-resources', function (event) {

        var type_ants_speed = [6, 6, 7, 15, 12, 3]; // rellenar desde django..

        // Si introducimos un número válido, mostramos el tiempo
        if (is_number_time($(this).val())){
            var speed_ant = type_ants_speed[0];
            var selector_div_time = "div.div-movement-resource-time";
            show_time_type_ant2($(this), speed_ant, selector_div_time);
        } else { // Si no, lo ocultamos.
            $(this).parent().siblings("div.div-movement-resource-time").hide();
        }

    });

    $('#main').on('keypress', 'input.ants-attack', function (event) {

        input_nodes = $(this).parent();
        var selector_ants = "ants-attack";

        // Seleccionamos el tipo de velocidad.
        var speed_ant = select_speed_type_ant(input_nodes, selector_ants);

        if (is_number_time($(this).val()) == ""){
            if (is_number_time(event.keyCode) && event.keyCode >= 49 && event.keyCode <= 57){
                speed_ant = select_keypress_speed_type_ant($(this), speed_ant);
            }
        } else {
            if (is_number_time($(this).val()) && is_number_time(event.keyCode) && event.keyCode >= 49 && event.keyCode <= 57){
                speed_ant = select_keypress_speed_type_ant($(this), speed_ant);
            }
        }

        if (speed_ant == -1) { // Si no hay ninguno ocultamos módulo de tiempo.
            $(this).parent().siblings("div.div-ants-attack-time").hide();
        }
        else {
            selector_div_time = "div.div-ants-attack-time";
            show_time_type_ant2($(this), speed_ant, selector_div_time);
        }
    });

    $('#main').on('keypress', 'input.ants-uphold', function (event) {

        input_nodes = $(this).parent();
        var selector_ants = "ants-uphold";

        // Seleccionamos el tipo de velocidad.
        var speed_ant = select_speed_type_ant(input_nodes, selector_ants);

        if (is_number_time($(this).val()) == ""){
            if (is_number_time(event.keyCode) && event.keyCode >= 49 && event.keyCode <= 57){
                speed_ant = select_keypress_speed_type_ant($(this), speed_ant);
            }
        } else {
            if (is_number_time($(this).val()) && is_number_time(event.keyCode) && event.keyCode >= 49 && event.keyCode <= 57){
                speed_ant = select_keypress_speed_type_ant($(this), speed_ant);
            }
        }
/*
        if (is_number_time(event.target.ALLOW_KEYBOARD_INPUT)){
            speed_ant = select_keypress_speed_type_ant($(this), speed_ant);
        }
*/
        if (speed_ant == -1) { // Si no hay ninguno ocultamos módulo de tiempo.
            $(this).parent().siblings("div.div-ants-uphold-time").hide();
        }
        else { // Si hay, lo mostramos.
            selector_div_time = "div.div-ants-uphold-time";
            show_time_type_ant($(this), speed_ant, selector_div_time);
        }
        
    });

    $('#main').on('keypress', 'input.input-resources', function (event) {

        var type_ants_speed = [6, 6, 7, 15, 12, 3]; // rellenar desde django..


        if (is_number_time($(this).val()) == ""){
            if (is_number_time(event.keyCode) && event.keyCode >= 49 && event.keyCode <= 57){
                //speed_ant = select_keypress_speed_type_ant($(this), speed_ant);
                var speed_ant = type_ants_speed[0];
                var selector_div_time = "div.div-movement-resource-time";
                show_time_type_ant($(this), speed_ant, selector_div_time);
            } else{
                $(this).parent().siblings("div.div-movement-resource-time").hide();
            }
            
        } else {
            if (is_number_time($(this).val()) && is_number_time(event.keyCode) && event.keyCode >= 49 && event.keyCode <= 57){
                //speed_ant = select_keypress_speed_type_ant($(this), speed_ant);

                var speed_ant = type_ants_speed[0];
                var selector_div_time = "div.div-movement-resource-time";
                show_time_type_ant($(this), speed_ant, selector_div_time);

            } else {
                $(this).parent().siblings("div.div-movement-resource-time").hide();
            }
        }

/*
        // Si introducimos un número válido, mostramos el tiempo
        if (is_number_time(event.target.ALLOW_KEYBOARD_INPUT)){
            var speed_ant = type_ants_speed[0];
            var selector_div_time = "div.div-movement-resource-time";
            show_time_type_ant($(this), speed_ant, selector_div_time);
        } else { // Si no, lo ocultamos.
            $(this).siblings("div.div-movement-resource-time").hide();
        }
*/
    });
    

    ko.applyBindings(game_vc);

});

